package com.mc.moring.main

//import kotlinx.android.synthetic.main.activity_main.*
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.mc.moring.BafBase.BAFBaseActivity
import com.mc.moring.BafBase.XViewPager
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.base.SaveZiLiPageTool
import com.mc.moring.bean.ZiLiPageUserDataBean
import com.mc.moring.login.LoginActivity
import com.mc.moring.main.adapter.TabFragmentAdapter
import com.mc.moring.main.fragment.HomeNewFragment
import com.mc.moring.main.fragment.PersonalFragment
import com.mc.moring.main.modle.LoanModle
import com.mc.moring.util.AppManager
import com.mc.moring.util.ToastUtils
import com.mc.moring.widge.LoadingDialog
import java.util.Date


class MainActivity : BAFBaseActivity<MainActivity>() {

    var userDataBean: ZiLiPageUserDataBean? = null

    private val navigation by lazy { findViewById<BottomNavigationView>(R.id.navigation) }

    private val viewPager by lazy { findViewById<XViewPager>(R.id.viewPager) }

    override lateinit var loadDingDialog: LoadingDialog

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun initLayout(): Int = R.layout.activity_main

    override fun initParameter(bundle: Bundle?) {}

    override fun afterInjectView() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        initUserLoginBean()
        initView()
        val isShowDialog:Boolean = intent.getBooleanExtra("isShowDialog", false)
        Log.e("----isShowDialog", isShowDialog.toString())
        val fragment = HomeNewFragment()
        val bundle = Bundle()
        if (isShowDialog){
            bundle.putBoolean("isShowDialog",true)
        } else {
            bundle.putBoolean("showDialog", false)
        }
        fragment.arguments = bundle

        navigation.itemIconTintList = null
        try {
//            BottomNavigationViewHelper.disableShiftMode(navigation)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    private fun initView() {
        loadDingDialog = LoadingDialog(this)
        AppManager.getAppManager().addActivity(this)
        val fragments = mutableListOf<Fragment>()
        fragments.add(0, HomeNewFragment().newInstance(0))
        fragments.add(1, PersonalFragment().newInstance(1))




        viewPager.setEnableScroll(false)
        viewPager.offscreenPageLimit = 2
        viewPager.adapter = TabFragmentAdapter(supportFragmentManager, fragments)
        viewPager.addOnPageChangeListener(onPageChangeListener)
        navigation.setOnNavigationItemSelectedListener(mOnListener)
    }

    override fun showMyLoading() {
        if (loadDingDialog == null) {
            loadDingDialog = LoadingDialog(this)
        }
        if (!loadDingDialog!!.isShowing() && !isFinishing) { //如果没有显示，就要显示
            loadDingDialog!!.show()
        }
    }

    override fun hideMyLoading(){
        if (loadDingDialog != null && loadDingDialog!!.isShowing) {
            loadDingDialog!!.dismiss()
        }
    }

    private fun bindBank() {
        val params: MutableMap<String, String> = java.util.HashMap()
        params["bankCode"] = "028"
        params["accountType"] = "1"
        params["accountNumber"] = "989999999"
        params["scenes"] = "info"
        LoanModle().bankbindAccount(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    runOnUiThread {
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onFaill(e: String) {

            }
        })
        val params1: MutableMap<String, String> = java.util.HashMap()
        LoanModle().bankgetPayBankList(params1, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    runOnUiThread {
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onFaill(e: String) {

            }
        })
    }


    private val mOnListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                viewPager.currentItem = 0
                isActionBarBlackColor(true)
                return@OnNavigationItemSelectedListener true
            }

            R.id.navigation_person -> {
                initUserLoginBean()
                if (!TextUtils.isEmpty(userDataBean?.token)) {
                    viewPager.currentItem = 1
                    isActionBarBlackColor(true)
                    return@OnNavigationItemSelectedListener true
                } else {
                    ToastUtils.showLong(this, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                    val intent = Intent(this, LoginActivity::class.java)
                    startActivity(intent)
                }
            }
        }
        false
    }

    @SuppressLint("SuspiciousIndentation")
    private fun initUserLoginBean() {
        val jsonString: String = SaveZiLiPageTool(this@MainActivity)
            .getKeyValue("user_info") ?: ""
        LogUtils.logE(" Main user login info>"+jsonString)
        if (!TextUtils.isEmpty(jsonString)) {
            userDataBean =
                Gson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            ZiLiPageUserDataBean.setInstance(userDataBean)
        }
    }

    private val onPageChangeListener = object : ViewPager.OnPageChangeListener {

        override fun onPageScrollStateChanged(position: Int) {}

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
        }

        override fun onPageSelected(position: Int) {}
    }

    var preTime: Long = 0
    val TWO_SECOND = (2 * 1000).toLong()

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            val currentTime: Long = Date().getTime()
            if (currentTime - preTime > TWO_SECOND) {
                try {
                    Toast.makeText(
                        this, "Press once to exit the program",
                        Toast.LENGTH_SHORT
                    ).show()
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                preTime = currentTime
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun hideLoading() {
    }

    override fun showLoading(msg: String?) {
    }

}
